package org.phmanago.utils;

import javax.imageio.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;

import javax.swing.ImageIcon;

public class ThumbMaker {

	public static ImageIcon getThumb(File f, int width, int height) {
		 Image image = Toolkit.getDefaultToolkit().getImage(f.getAbsolutePath());
         MediaTracker mediaTracker = new MediaTracker(new Container());
         mediaTracker.addImage(image, 0);
         try {
             mediaTracker.waitForID(0);
         } catch (InterruptedException e) {}

         double thumbRatio = (double)width / (double)height;
         int imageWidth = image.getWidth(null);
         int imageHeight = image.getHeight(null);

         double imageRatio = (double)imageWidth / (double)imageHeight;
         if (thumbRatio < imageRatio) {
           height = (int)(width / imageRatio);
         } else {
           width = (int)(height * imageRatio);
         }

         BufferedImage thumbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
         Graphics2D graphics2D = thumbImage.createGraphics();
         graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
         graphics2D.drawImage(image, 0, 0, width, height, null);
         
         return new ImageIcon(thumbImage);
	}
}
